<template>
  <div class="echarts-container">
    <el-card shadow="hover" class="rounded-lg overflow-hidden card">
      <div class="flex space-x-2">
        <h2>{{ routerParams }}( {{ title }} )故障维修单分布</h2>
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="时间范围">
              <el-date-picker
                v-model="timeFrame"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :clearable="true">
              </el-date-picker>
            </el-form-item>
          <el-form-item label="机台类型">
            <el-select size="small" 
            v-model="typeCode" 
            placeholder="请选择机台类型"
            @visible-change="getTypeCodeOptions">
            <el-option value="" label="整体"></el-option>
            <el-option
              v-for="item in typeCodeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-input
              size="small"
              style="width: 100%;"
              placeholder="设置故障标准"
              v-model="Standard"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="onStandard">
            确定
            </el-button>
            <el-button size="small" @click="onReset">重置</el-button>
          </el-form-item>
            </el-form>
        </div>
    </el-card>
    <el-card shadow="hover" class="rounded-lg overflow-hidden card">
      <div class="flex justify-between items-center mb-4 px-4 pt-2" style="margin-bottom: 20px;">
        <div class="flex space-x-2">
          <el-button size="small" type="primary" icon="el-icon-refresh" @click="RefreshChart(1)">
            刷新
          </el-button>
          <el-button size="small" type="text" icon="el-icon-zoom-in" @click="ZoomIn">
            放大
          </el-button>
          <el-button size="small" type="text" icon="el-icon-zoom-out" @click="ZoomOut">
            缩小
          </el-button>
        </div>
      </div>
      <!-- 折线图组件 -->
      <div ref="Ref" class="w-full h-[800px]"></div>
      <div class="px-4 py-2 text-sm text-gray-500">
    <table class="bordered-table">
      <tbody>
        <tr>
          <th>维修单数</th>
          <td v-for="(item, index) in singular" :key="index">
            {{ item }}
          </td>
        </tr>
        <tr>
          <th>百分比</th>
          <td v-for="(item, index) in percentage" :key="index">
            {{ item }}
          </td>
        </tr>
        <tr>
          <th>累积%</th>
          <td v-for="(item, index) in accumulate" :key="index">
            {{ item }}
          </td>
        </tr>
      </tbody>
    </table>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from 'echarts';
import { debounce } from 'lodash-es';
import { getToken } from "@/utils/auth";

export default {
  name: 'equipmentWeeklyReport',
  data() {
    return {
      routerParams: '', //父级路由数据
      title: '',
      timeFrame: '',
      typeCode: '',  //机台类型
      Standard: '', //标准
      typeCodeOptions: [], //下拉框
      singular: [],
      percentage: [],
      accumulate: [], //表格
      // 折线图表
      Chart: null,
      ChartOption: {
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        title: {
          text: this.title+'设备故障分布',
          left: 'center',
          textStyle: {
            color: '#333',
            fontWeight: 'normal',
            fontSize: 16
          }
        },
        // 提示框
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: { color: '#333' },
          padding: 10,
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);',
          // 悬停内容
          formatter: (params) => {
            let result = `<div class="font-semibold">${params[0].name}</div>`;
            params.forEach(item => {
              const color = item.color;
              const value = item.value;
              const name = item.seriesName;
              result += `
                <div class="flex items-center mt-1">
                  <span class="inline-block w-3 h-3 rounded-full mr-2" style="background-color: ${color}"></span>
                  <span class="mr-2">${name}:</span>
                  <span class="font-semibold">${value}</span>
                </div>
              `;
              if (value !== this.ChartOption.series[1].markLine.data[0].yAxis) {
                const deviation = value - this.ChartOption.series[1].markLine.data[0].yAxis;
                const deviationText = deviation > 0 
                  ? `<span class="text-green-500">${deviation} (优于标准)</span>` 
                  : `<span class="text-red-500">${deviation} (低于标准)</span>`;
                result += `
                  <div class="ml-5 text-xs mt-0.5">
                    <span class="text-gray-500">与标准差值:</span> ${deviationText}
                  </div>
                `;
              }
            });
            return result;
          }
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          bottom: '5%',
          left: 'center',
          pageButtonItemGap: 5,
          pageButtonColor: '#666',
          pageButtonActiveColor: '#409EFF',
          data: ['维修单数','百分比','标准']
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        // 工具栏
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              name: this.title+'设备故障分布',
              title: '保存为图片',
              type: 'png',
              backgroundColor: 'white'
            },
            dataView: {
              title: '数据视图',
              readOnly: true,
              buttonColor: '#409EFF',
              buttonTextStyle: { color: '#fff' }
            }
          },
          right: '5%',
          top: '2%'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#666',
            // formatter: function (value) {
            //   if (value.includes('W')) {
            //     return value.replace('W', '周 ');
            //   }
            //   return value;
            // }
          },
          boundaryGap: true
        },
        yAxis: [
          {
          type: 'value',
          name: '次数',
          nameLocation: 'middle',
          nameGap: 30,
          min: 0,
          splitNumber: 5,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#666',
            formatter: function (value) {
              return value;
            }
          },
          splitLine: {
            lineStyle: {
              color: '#eee'
            }
          }
        },
        {
          type: 'value',
          name: '百分比',
          position: 'right',
          nameLocation: 'middle',
          nameGap: 30,
          min: 0,
          max:100,
          splitNumber: 5,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#666',
            formatter: function (value) {
              return value + '%';
            }
          },
          splitLine: {
            lineStyle: {
              color: '#eee'
            }
          }
        }
      ],
        series: [
          {
            name: '维修单数',
            type: 'bar',
            data: [],
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            showSymbol: true,
            // 数据点样式
            itemStyle: {
              color: '#409EFF',
              borderWidth: 2,
              borderColor: '#fff',
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.2)'
            },
            // 线条样式
            lineStyle: {
              width: 3,
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 1, y2: 0,
                colorStops: [
                  { offset: 0, color: '#409EFF' },
                  { offset: 1, color: '#87CEEB' }
                ]
              },
              shadowBlur: 10,
              shadowColor: 'rgba(64, 158, 255, 0.3)'
            },
            // 区域填充样式
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(64, 158, 255, 0.4)' },
                  { offset: 1, color: 'rgba(64, 158, 255, 0)' }
                ]
              }
            },
            // 标记点配置
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ],
              itemStyle: {
                color: '#f56c6c'
              },
              label: {
                color: '#333'
              }
            },
            // 标记线配置
            // markLine: {
            //   data: [
            //     { type: 'average', name: '平均值' }
            //   ],
            //   lineStyle: {
            //     type: 'dashed',
            //     color: '#999'
            //   }
            // }
          },
          {
            name: '标准',
            type: 'line',
            markLine: {
              silent: true,
              symbol: 'none',
              label: {
                show: true,
                position: 'end',
                formatter: '{c}'
              },
              lineStyle: {
                type: 'dashed',
                color: '#67c23a',
                width: 2,
                shadowBlur: 5,
                shadowColor: 'rgba(103, 194, 58, 0.3)'
              },
              data: [
                {
                  yAxis: 0 // 这里设置参考线的值
                }
              ]
            }
          },
          {
            name: '百分比',
            type: 'line',
            data: [],
            yAxisIndex: 1,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            showSymbol: true,
            // 数据点样式
            itemStyle: {
              color: '#409EFF',
              borderWidth: 2,
              borderColor: '#fff',
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.2)'
            },
            // 线条样式
            lineStyle: {
              width: 3,
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 1, y2: 0,
                colorStops: [
                  { offset: 0, color: '#FF9F43' },
                  { offset: 1, color: '#FF5252' }
                ]
              },
              shadowBlur: 10,
              shadowColor: 'rgba(64, 158, 255, 0.3)'
            },
            // 区域填充样式
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(64, 158, 255, 0.4)' },
                  { offset: 1, color: 'rgba(64, 158, 255, 0)' }
                ]
              }
            },
            // 标记点配置
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ],
              itemStyle: {
                color: '#f56c6c'
              },
              label: {
                color: '#333'
              }
            },
            // 标记线配置
            // markLine: {
            //   data: [
            //     { type: 'average', name: '平均值' }
            //   ],
            //   lineStyle: {
            //     type: 'dashed',
            //     color: '#999'
            //   }
            // }
          }
        ]
      },
      ChartZoom: 1
    };
  },
  mounted() {
    this.initChart();
    // 初始化放大
    this.ZoomIn();
    // 使用防抖处理窗口大小变化，避免频繁重绘
    this.resizeHandler = debounce(() => {
      this.resizeChart();
    }, 100);
    window.addEventListener('resize', this.resizeHandler);
  },

  beforeDestroy() {
    if (this.Chart) {
      this.Chart.dispose();
      this.Chart = null;
    }
    window.removeEventListener('resize', this.resizeHandler);
  },
  methods: {
    // 获取下拉菜单
    async getTypeCodeOptions(){
      const token = getToken();
      const params = {};
      const response = await axios.get(
          `${process.env.VUE_APP_BASE_API}/wareHouses/equipmentId`,
          {
            params,
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        this.typeCodeOptions = response.data;

    },
    // 获取折线图数据
    async getChartOption(value){
      const token = getToken();
      this.routerParams= this.$route.params.name;
      const params = {};
       if(this.timeFrame){
        params.startDate = this.timeFrame[0];
        params.endDate = this.timeFrame[1];
      }
      if(value){
        this.routerParams = value;
      }
      const response = await axios.get(
          `${process.env.VUE_APP_BASE_API}/wareHouses/lastWeek/${this.routerParams}`,
          {
            params,
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        this.ChartOption.xAxis.data = response.data.failurePhenomenon;
        this.ChartOption.series[0].data = response.data.repairCount;
        this.ChartOption.series[2].data = response.data.repairPercentage;
        this.title = response.data.title;
        this.singular = response.data.repairCount;;
        this.percentage = response.data.repairPercentage;
        let sun =0;
        if(this.percentage){
          this.percentage.forEach(percentage =>{
            sun += parseFloat(percentage);
            this.accumulate.push(sun.toFixed(2));
          })
        }
    },
    // 初始化折线图
    async initChart(value) {
      await this.getChartOption(value);
      const chartDom = this.$refs.Ref;
      this.Chart = echarts.init(chartDom);
      
      // 设置图表配置项
      if (this.ChartOption) {
        this.Chart.setOption(this.ChartOption);
      }
      
      // 添加图表事件监听
      this.Chart.on('click', (params) => {
        if (params.componentType === 'series') {
          this.$message({
            message: `您点击了 ${params.name} 的 ${params.seriesName}: ${params.value}`,
            type: 'info'
          });
        }
      });
    },
    resizeChart() {
      if (this.Chart) {
        this.Chart.resize();
      }
    },

    // 刷新
    async RefreshChart(value) {
      if(value == 1){
        await this.getChartOption(null);
      }
      if (this.Chart) {
        this.Chart.setOption(this.ChartOption,true);
        this.$message({
          message: '图表数据已刷新',
          type: 'success'
        });
      }
    },
    // 扩大
    ZoomIn() {
      if (this.ChartZoom < 1.5) {
        this.ChartZoom += 0.1;
        this.updateChartSize();
      }
    },
// 缩小
    ZoomOut() {
      if (this.ChartZoom > 0.7) {
        this.ChartZoom -= 0.1;
        this.updateChartSize();
      }
    },
    // 刷新大小
    updateChartSize() {
      const chartDom = this.$refs.Ref;
      chartDom.style.height = `${800 * this.ChartZoom}px`;
      this.resizeChart();
    },
    // 查询
    async onSubmit(){
      await this.getChartOption(this.typeCode);
      this.ChartOption.title.text = this.title + '设备故障分布';
      this.RefreshChart();
      this.onReset();
    },
    // 确定设置标准
    onStandard(){
      if(this.Standard){
        this.ChartOption.series[1].markLine.data[0].yAxis = this.Standard;
        this.Standard = '';
        this.RefreshChart();
      }
    },
    // 重置
    onReset(){
      this.Standard = '';
      this.typeCode = ''; //机台类型
      this.timeFrame= '';
    }
  }
};
</script>

<style scoped>
.card{
  margin-bottom: 10px;
}
/* 折线统计图 */
.echarts-container {
  width: 100%;
  height: 100%;
  padding: 10px;
}

/* 自定义tooltip样式 */
.el-tooltip__popper {
  max-width: 300px;
  min-height: 300px;
}
/* 表格 */
.bordered-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
}
.bordered-table th, .bordered-table td {
  padding: 10px 15px;
  border: 1px solid #ddd;
  text-align: center;
}
.bordered-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}
</style>